<template>
  <!-- 弹窗始终挂载，用 v-show 控制显示 -->
  <div v-show="visible" class="overlay" @click.self="close">
    <div class="modal">
      <canvas ref="qrCanvas" width="200" height="200"></canvas>
      <p style="margin-top: 10px">请使用微信扫码登录</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, nextTick, onMounted } from "vue";
import QRCode from "qrcode";

interface Props {
  visible: boolean; // 父组件控制显示
  wxUrl: string; // 微信扫码 URL
  onSuccess?: (data: any) => void; // 扫码成功回调，可选
}

const props = defineProps<Props>();
const emit = defineEmits<{
  (e: "update:visible", val: boolean): void;
}>();

const qrCanvas = ref<HTMLCanvasElement>();

// 关闭弹窗
const close = () => {
  emit("update:visible", false);
};

// 打印 props，确保接收到父组件数据
onMounted(() => {
  console.log("WxLoginModal mounted, props:", props);
});

// 监听 visible 或 wxUrl 改变，渲染二维码
watch(
  [() => props.visible, () => props.wxUrl],
  async ([visible, url]) => {
    console.log("WxLoginModal visible:", visible, "wxUrl:", url);
    if (visible && url && qrCanvas.value) {
      await nextTick(); // 等 DOM 挂载
      try {
        await QRCode.toCanvas(qrCanvas.value, url, { width: 200 });
        console.log("二维码已生成到 canvas");
      } catch (err) {
        console.error("二维码生成失败:", err);
      }
    }
  },
  { immediate: true }
);
</script>

<style scoped>
.overlay {
  position: fixed;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background: rgb(0 0 0 / 50%);
}
.modal {
  padding: 20px;
  text-align: center;
  background: white;
  border-radius: 8px;
}
canvas {
  display: block;
  margin: 0 auto;
}
</style>
